package com.future.hedongjun.mine.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.ToastUtils;
import com.future.baselib.view.IosAlertDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.Contant;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.mine.bean.DeliveryAddressBean;
import com.google.gson.Gson;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * description: 编辑收货地址
 * autour: gxcheng
 * date: 2017/9/14 1:03
 */
public class DeliveryAddressEditActivity extends BaseActivity {

    @BindView(R.id.delivery_name_et)
    EditText mDeliveryNameEt;
    @BindView(R.id.delivery_phone_et)
    EditText mDeliveryPhoneEt;
    @BindView(R.id.delivery_address_tv)
    TextView mDeliveryAddressTv;
    @BindView(R.id.delivery_house_number_et)
    EditText mDeliveryHouseNumberEt;
    @BindView(R.id.delivery_address_default_cb)
    CheckBox mDefaultAddressCb;
    @BindView(R.id.layout_1)
    View layout1;
    @BindView(R.id.layout_2)
    View layout2;
    @BindView(R.id.layout_3)
    View layout3;
    @BindView(R.id.layout_4)
    View layout4;

    private String mAddressId;
    private DeliveryAddressBean mDeliveryAddressBean;
    private String province;
    private String city;
    private String area;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_address_edit);
        ButterKnife.bind(this);
//        setTitle("编辑收货地址");

        initClicks();
        mAddressId = getIntent().getStringExtra(Contant.KEY_ADDRESS_ID);
        if (!TextUtils.isEmpty(mAddressId)) {
            mDeliveryAddressBean = (DeliveryAddressBean) getIntent().getSerializableExtra("address");
            setTitle("编辑收货地址");
            setTitleRight("删除", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IosAlertDialog alertDialog = new IosAlertDialog(mContext).builder();
                    alertDialog.setTitle("提示").setMsg("确定要删除地址么？").setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            delAddress();
                        }
                    }).setNegativeButton("取消", null).show();
                }
            });
            bindViews(mDeliveryAddressBean);
        } else {
            mDeliveryAddressBean = new DeliveryAddressBean();
            setTitle("新增收货地址");
        }
    }

    private void initClicks() {

        mDeliveryAddressTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AndPermission
                        .with(DeliveryAddressEditActivity.this)
                        .runtime()
                        .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.READ_PHONE_STATE)
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                startActivityForResult(DeliveryAddressSelectActivity.class, Contant.const_10010);
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                toast("请开启权限，以使用功能");
                            }
                        })
                        .start();
            }
        });

        /*保存*/
        findViewById(R.id.delivery_address_save_btn_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loge("tag", "mDefaultAddressCb.isChecked()---" + mDefaultAddressCb.isChecked());
                if (TextUtils.isEmpty(mDeliveryNameEt.getText().toString())) {
                    ToastUtils.shortToast(mContext, "请输入收货人姓名");
                    return;
                }
                if (TextUtils.isEmpty(mDeliveryPhoneEt.getText().toString())) {
                    ToastUtils.shortToast(mContext, "请输入收货人手机号");
                    return;
                }
                if (TextUtils.isEmpty(mDeliveryAddressTv.getText().toString())) {
                    ToastUtils.shortToast(mContext, "请选择收货地址");
                    return;
                }
                if (TextUtils.isEmpty(mDeliveryHouseNumberEt.getText().toString())) {
                    ToastUtils.shortToast(mContext, "请输入门牌号");
                    return;
                }

                doSubmit();
            }
        });

    }

    private void doSubmit() {
        TreeMap<String, Object> treeMap = new TreeMap<>();
        treeMap.put("token", MyApp.getInstance().getUserInfo().getToken());
        treeMap.put("isdefault", mDefaultAddressCb.isChecked() ? "1" : "0");
        treeMap.put("phone", mDeliveryPhoneEt.getText().toString());
        treeMap.put("name", mDeliveryNameEt.getText().toString());
        treeMap.put("location",  mDeliveryAddressTv.getText().toString());
        treeMap.put("detail", mDeliveryHouseNumberEt.getText().toString());
//        treeMap.put("region",province+","+city+","+area);
        String path = "";
        if (!TextUtils.isEmpty(mAddressId)) {
            treeMap.put("id", mAddressId);
            path = "/addons/litestore/api.adress/edit";
        }else{
            path = "/addons/litestore/api.adress/add";
        }
        Log.e("tag", "doSubmit: " + new Gson().toJson(treeMap));
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setPath(path)
                .addParams(treeMap)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        setResult(RESULT_OK);
                        finish();
                    }
                }).start(new DefaultResponse());


    }

    private void initDatas() {
//        showLoadingDialog();
//        TreeMap<String, Object> treeMap = new TreeMap<>();
//        treeMap.put("userToken", MyApp.getInstance().getUserToken());
//        treeMap.put("id", mAddressId);
//        HttpUtils httpUtils = new HttpUtils<DefaultResponse>(mContext, "_receipt_002", treeMap, new HttpLisenter<DefaultResponse>() {
//            @Override
//            public void onSuccess(DefaultResponse response) {
//                dissmissLoadingDialog();
//                DeliveryAddressBean bean = new Gson().fromJson(response.getResponseJson(), DeliveryAddressBean.class);
//                bindViews(bean);
//            }
//
//            @Override
//            public void onFail(String message) {
//                dissmissLoadingDialog();
//                ToastUtils.shortToast(mContext, message);
//            }
//        });
//        httpUtils.doStart(new DefaultResponse());
    }

    private void bindViews(DeliveryAddressBean deliveryAddressBean) {
        mDeliveryNameEt.setText(deliveryAddressBean.getName());
        mDeliveryPhoneEt.setText(deliveryAddressBean.getPhone());
        mDeliveryAddressTv.setText(deliveryAddressBean.getLocation());
        mDeliveryHouseNumberEt.setText(deliveryAddressBean.getDetail());
        if (Integer.parseInt(deliveryAddressBean.getIsdefault()) == 1) {
            mDefaultAddressCb.setChecked(true);
        }
        mDeliveryAddressBean = deliveryAddressBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Contant.const_10010 && resultCode == RESULT_OK) {
            PoiItem addressPoiItem = data.getParcelableExtra("addressModel");
            province = addressPoiItem.getProvinceName();
            city = addressPoiItem.getCityName();
            area = addressPoiItem.getAdName();
            mDeliveryAddressTv.setText(province + city + area + addressPoiItem.getSnippet());

            mDeliveryAddressBean.setLocation(mDeliveryAddressTv.getText().toString());
//            mDeliveryAddressBean.setLat(String.valueOf(addressPoiItem.getLatLonPoint().getLatitude()));
//            mDeliveryAddressBean.setLng(String.valueOf(addressPoiItem.getLatLonPoint().getLongitude()));

        }
    }

    private void delAddress() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setPath("/addons/litestore/api.adress/del")
                .addParam("id",mAddressId)
                .addParam("token",MyApp.getInstance().getUserInfo().getToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        toast("删除成功");
                        setResult(RESULT_OK);
                        finish();
                    }
                }).start(new DefaultResponse());
    }
}
